package com.roubsite.admin.dao.user;

import java.sql.Types;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.roubsite.admin.bean.RsUsers;
import com.roubsite.database.bean.Record;
import com.roubsite.database.dao.DataSet;
import com.roubsite.database.dao.EntityDao;
import com.roubsite.utils.StringUtils;
import com.roubsite.utils.UuidUtils;

public class UserDao extends EntityDao implements IUserDao {

	/**
	 * 获取用户基本信息
	 */

	@Override
	public Map getUserInfo(String username) {
		Map map = this.find(
				"SELECT  U.EXPIRED_TIME,U.DENIED_VISITS, U.LAST_DENIED_TIME,U.USER_ID, U.USER_NAME, U.USER_PASSWORD, U.USER_STATUS, O.ORGAN_ID , G.ORGAN_CODE, G.ORGAN_NAME, G.ORGAN_TYPE, G.PARENT_ID FROM RS_USERS U "
						+ "LEFT JOIN RS_USERS_ORGAN O ON U.USER_ID = O.USER_ID LEFT JOIN RS_ORGAN G ON O.ORGAN_ID = G.ORGAN_ID WHERE U.USER_NAME =?",
				new String[] { username }, new int[] { Types.VARCHAR });
		return map;
	}

	/**
	 * 获取用户菜单
	 */
	@Override
	public LinkedList<String> getUserAuthorizedUrl(String userId) {
		List list = this.query("SELECT MO.URL AS URL FROM RS_USERS_ROLE UR, RS_ROLE_MENU RM, RS_MENU_OP MO "
				+ "WHERE (UR.ROLE_ID = RM.ROLE_ID AND MO.MENU_ID = RM.MENU_ID AND MO.URL IS NOT NULL AND MO.URL != '' AND UR.USER_ID = ?) "
				+ "UNION ALL SELECT MO.MENU_URL AS URL FROM RS_USERS_ROLE UR, RS_ROLE_MENU RM, RS_MENU MO "
				+ "WHERE (UR.ROLE_ID = RM.ROLE_ID AND MO.MENU_ID = RM.MENU_ID AND MO.MENU_URL IS NOT NULL AND MO.MENU_URL != '' AND UR.USER_ID = ?)",
				new String[] { userId, userId }, new int[] { Types.VARCHAR, Types.VARCHAR });
		LinkedList<String> l = new LinkedList<>();
		for (int i = 0; i < list.size(); i++) {
			Map m = (Map) list.get(i);
			l.add((String) m.get("URL"));
		}
		return l;
	}

	/**
	 * 获取用户基本信息
	 */
	@Override
	public DataSet getUserInfoById(String userId) {
		DataSet ds = this.queryBean("SELECT * FROM RS_USERS WHERE USER_ID =?", new String[] { userId },
				new int[] { Types.VARCHAR }, false, 0, 0, RsUsers.class);
		return ds;
	}

	/**
	 * 根据请求获取相应数据
	 */
	@Override
	public DataSet queryd(Record record, int start, int rows) {
		return this.queryBean(record.toBean(RsUsers.class), null, true, start, rows);
	}

	@Override
	public int saveData(Record record, Class<?> bean) {
		return this.save(record, bean);
	}

	@Override
	public int del(List ids) throws Exception {
		String tableName = "RS_USERS";
		String keyField = "USER_ID";
		StringBuffer delSql = new StringBuffer("DELETE FROM " + tableName + " WHERE " + keyField + " IN (");
		for (int i = 0; i < ids.size(); i++) {
			delSql.append("'");
			delSql.append(ids.get(i));
			delSql.append("',");
		}
		String sql = delSql.substring(0, delSql.length() - 1);
		sql = sql + ")";

		return this.excute(sql, new Object[] {}, new int[] {});
	}

	@Override
	public String[] getUserRoles(String userId) {
		List roleIds = this.query(
				"SELECT R.ROLE_ID FROM RS_ROLES R LEFT JOIN RS_USERS_ROLE U ON R.ROLE_ID = U.ROLE_ID WHERE U.USER_ID = ?",
				new String[] { userId }, new int[] { Types.VARCHAR });
		List ids = new ArrayList<>();
		for (int i = 0; i < roleIds.size(); i++) {
			ids.add(((Map) roleIds.get(i)).get("ROLE_ID"));
		}
		return (String[]) ids.toArray(new String[] {});
	}

	@Override
	public int editUserRole(String userId, String[] roleId) {
		int ret = this.excute("DELETE FROM RS_USERS_ROLE WHERE USER_ID=?", new String[] { userId },
				new int[] { Types.VARCHAR });

		for (int i = 0; i < roleId.length; i++) {
			if (StringUtils.isNotEmpty(roleId[i])) {
				String sql = new String("INSERT INTO RS_USERS_ROLE VALUES(?,?,?)");
				this.excute(sql, new String[] { UuidUtils.getUuid(), userId, roleId[i] },
						new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
			}
		}
		return 1;
	}

	@Override
	public DataSet queryUserOrgan(Record record, int start, int rows) {
		StringBuffer sql = new StringBuffer(
				"SELECT * FROM RS_USERS U LEFT JOIN RS_USERS_ORGAN O ON U.USER_ID = O.USER_ID WHERE 1=1");
		List<Object> args = new LinkedList<Object>();
		List<Integer> types = new LinkedList<Integer>();
		if (StringUtils.isNotEmptyObject(record.get("ORGAN_ID")) && !"root".equals(record.get("ORGAN_ID"))) {
			sql.append(" AND ORGAN_ID = ?");
			args.add(record.get("ORGAN_ID"));
			types.add(VARCHAR);
		}
		if (StringUtils.isNotEmptyObject(record.get("USER_NAME"))) {
			sql.append(" AND USER_NAME = ?");
			args.add(record.get("USER_NAME"));
			types.add(VARCHAR);
		}
		if (StringUtils.isNotEmptyObject(record.get("STATUS"))) {
			sql.append(" AND USER_STATUS = ?");
			args.add(record.get("STATUS"));
			types.add(VARCHAR);
		}
		int[] _types = new int[types.size()];
		for (int i = 0; i < types.size(); i++) {
			_types[i] = types.get(i);
		}
		return this.queryBean(sql.toString(), args.toArray(), _types, true, start, rows, RsUsers.class);
	}

	@Override
	public int editUserOrgan(String userId, String organId) {
		int ret = this.excute("DELETE FROM RS_USERS_ORGAN WHERE USER_ID=?", new String[] { userId },
				new int[] { Types.VARCHAR });
		String sql = new String("INSERT INTO RS_USERS_ORGAN VALUES(?,?)");
		ret = this.excute(sql, new String[] { userId, organId }, new int[] { Types.VARCHAR, Types.VARCHAR });
		return ret;
	}

	@Override
	public int upStatusByName(String username, String userStatus) {
		return this.excute(
				"UPDATE RS_USERS SET USER_STATUS = ?,  LOCK_TIME = NULL, EXPIRED_TIME = NULL, DENIED_VISITS = '0' WHERE USER_NAME = ?",
				new String[] { userStatus, username }, new int[] { Types.VARCHAR, Types.VARCHAR });
	}

	@Override
	public Map getUserSystem() {
		return this.find("SELECT LOCK_TIME,DENIED_NUM,AUTO_LIFTING FROM RS_USER_SYSTEM WHERE SYSTEM_STATUS='1' ", null,
				null);
	}

	@Override
	public int updateNum(String username, String USER_STATUS, String LOCK_TIME, String EXPIRED_TIME,
			String DENIED_VISITS, String LAST_DENIED_TIME) {
		return this.excute(
				"UPDATE RS_USERS SET USER_STATUS = ?,  LOCK_TIME = ?, EXPIRED_TIME = ?, DENIED_VISITS = ?, LAST_DENIED_TIME = ? WHERE USER_NAME=?",
				new String[] { USER_STATUS, LOCK_TIME, EXPIRED_TIME, DENIED_VISITS, LAST_DENIED_TIME, username },
				new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
	}

	@Override
	public void insertLog(String ip, String userName, String describe, String page, String uri, String ua) {
		String sql = "INSERT INTO RS_SYSTEM_LOG(ID, USER_ID, IP, PAGE, URI, LOG_DESCRIBE, UA,CREATE_TIME) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
		this.excute(sql,
				new String[] { UuidUtils.getUuid(), "", ip, page, uri, describe, ua, StringUtils.getUnixDate() },
				new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
						Types.VARCHAR, Types.VARCHAR });
	}

	@Override
	public void register(String userId, String username, String password, String roleId, String organId) {
		String insertUser = "INSERT INTO RS_USERS(USER_ID, USER_NAME, USER_PASSWORD, USER_STATUS, CREATE_TIME, LOCK_TIME, EXPIRED_TIME, PWD_UP_TIME, PWD_TIME, DENIED_VISITS, LAST_DENIED_TIME) VALUES"
				+ " (?, ?, ?, '1', ?, NULL, NULL, ?, NULL, '0', NULL)";
		String insertUserRole = "INSERT INTO RS_USERS_ROLE(RULE_ID, USER_ID, ROLE_ID) VALUES (?, ?, ?)";
		String insertUserOrgan = "INSERT INTO RS_USERS_ORGAN(USER_ID, ORGAN_ID) VALUES (?, ?)";
		this.excute(insertUser,
				new String[] { userId, username, password, StringUtils.getUnixDate(), StringUtils.getUnixDate() },
				new int[] { VARCHAR, VARCHAR, VARCHAR, VARCHAR, VARCHAR });
		this.excute(insertUserRole, new String[] { UuidUtils.getUuid(), userId, roleId },
				new int[] { VARCHAR, VARCHAR, VARCHAR });
		this.excute(insertUserOrgan, new String[] { userId, organId }, new int[] { VARCHAR, VARCHAR });

	}

	@Override
	public boolean isInSystem(String userName) {
		List l = this.query("SELECT * FROM RS_USERS WHERE USER_NAME = ?", new String[] { userName },
				new int[] { VARCHAR });
		return l.size() > 0;
	}

	@Override
	public int updatePassword(String encodePassword, String uid) {
		String sql = "UPDATE RS_USERS SET USER_PASSWORD = ? WHERE USER_ID = ?";
		return this.excute(sql, new String[] { encodePassword, uid }, new int[] { VARCHAR, VARCHAR });
	}
}
